#!/usr/bin/python3
# -*- coding:utf-8 -*-
"""
@author: henry_oulen
@file: json_tools.back.py
@time: 2023/8/28 9:27
@desc: 优化代码
"""
import base64
import datetime
import hashlib
import json
import os
import queue
import random
import re
import shutil
import time
import tkinter
from io import BytesIO
from sqlite3 import IntegrityError
from tkinter import ANCHOR, END, SOLID
from urllib.request import urlopen

import psutil
import requests
import ttkbootstrap as ttk
import win32api
import win32con
import win32gui
from PIL import Image
from ttkbootstrap import Style, DateEntry, Checkbutton

from json_tool.baidu_api import get_access_token
from json_tool.config_json_tool import app_id, api_key, secret_key_wx, secret_key_fy, gaode_key, ad_code
from json_tool.icon import Icon
from json_tool.utils import day_laster, get_content

request_thread = None
import threading

# 创建一个队列用于线程间通信
result_queue = queue.Queue()

from sqlalchemy import create_engine, Column, Integer, String, Text
from sqlalchemy.orm import declarative_base
from sqlalchemy.orm import sessionmaker

# 创建基类
Base = declarative_base()
global_time_status = True


class System_info(Base):
    __tablename__ = 'system_info'
    id = Column(Integer, primary_key=True)
    name = Column(String(50))
    value = Column(Integer)
    text = Column(String(50))


class Day_info(Base):
    __tablename__ = 'day_info'
    id = Column(Integer, primary_key=True)
    this_date = Column(String(50))
    key = Column(String(50))
    content = Column(Text)


# 连接到 SQLite 数据库
engine = create_engine('sqlite:///json_tool.db', echo=True)
Base.metadata.create_all(engine)


def get_session():
    # 创建会话
    session_instance = sessionmaker(bind=engine)()
    return session_instance


def initialize_system_config(session, name, default_value=None, use_text=False):
    """初始化系统配置（优化版）"""
    try:
        config = session.query(System_info).filter_by(name=name).first()
        if not config:
            config = System_info(
                name=name,
                value=default_value if not use_text else None,
                text=str(default_value) if use_text else None)
            session.add(config)
            session.commit()
        return config
    except IntegrityError:
        session.rollback()
        return session.query(System_info).filter_by(name=name).first()


# 初始化配置
with get_session() as db_session:
    current_time_str = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    initialize_system_config(db_session, "switch", default_value=0)
    initialize_system_config(db_session, "pick_date", default_value=current_time_str, use_text=True)
    initialize_system_config(db_session, "growth_date", default_value=current_time_str, use_text=True)
    initialize_system_config(db_session, "pregnancy_cycle", default_value=0)
    initialize_system_config(db_session, "ad_code", default_value=ad_code)
    # 直接获取配置值
    pick_date = db_session.query(System_info).filter_by(name="pick_date").first().text
    growth_date = db_session.query(System_info).filter_by(name="growth_date").first().text


class JsonTools:

    def __init__(self, my_wind):
        self.window = my_wind
        self.style = Style(theme='darkly')
        with open('tmp.ico', 'wb') as tmp:
            tmp.write(base64.b64decode(Icon().img))
        self.window.iconbitmap('tmp.ico')
        os.remove('tmp.ico')

        self.session = get_session()
        # width = window.winfo_screenwidth()
        self.window.title('小工具 @author  >> henry.oulen@gmail.com   date:2025/03/05 v_0.0.2')

        # 获取屏幕尺寸计算参数，使窗口显示再屏幕中央
        # screen_width = self.window.winfo_screenwidth()
        # screen_height = self.window.winfo_screenheight()
        self._width = 1920
        self._height = 1080
        # window_size = f'{self._width}x{self._height}+{round((screen_width - self._width) / 2)}+{round((screen_height - self._height) / 2)}'  # round去掉小数
        self.window.wm_state("zoomed")  # 设置打开的窗口最大化
        self.window.config(bg="#1E1F22")

        # 周几
        self.dat_num_label = tkinter.Label(self.window, text='', fg="#a9b7c6", font="等线 24 bold", bg="#1E1F22")
        self.dat_num_label.place(relx=0.34, rely=0.02, relwidth=0.05, relheight=0.05)

        # 当前时间
        self.now_time_label = tkinter.Label(self.window, text='', fg='#a9b7c6', font="等线 24 bold", bg="#1E1F22")
        self.now_time_label.place(relx=0.39, rely=0.02, relwidth=0.2, relheight=0.05)

        # 时间选择
        self.can_time_stamp_input = DateEntry(self.window, bootstyle="success", dateformat='%Y-%m-%d %H:%M:%S',
                                              startdate=datetime.datetime.strptime(pick_date, '%Y-%m-%d %H:%M:%S'))
        self.can_time_stamp_input.place(relx=0.76, rely=0.02, relwidth=0.1, relheight=0.05)

        # 提交按钮
        self.get_time_submit = tkinter.Button(self.window, text="提交", command="get_time_submit_method",
                                              activebackground="#0f73ef", borderwidth=1, highlightthickness=1,
                                              relief=SOLID,
                                              highlightbackground="#a9b7c6",
                                              font="等线 12 bold", background="#1E1F22", foreground="#a9b7c6")
        self.get_time_submit.bind("<Button-1>", self.get_time_submit_method)
        self.get_time_submit.place(relx=0.86, rely=0.03, relwidth=0.03, relheight=0.03)

        # 倒计时
        self.can_time_stamp_show_input = tkinter.Label(self.window, text='', font="等线 19 bold", background="#1E1F22",
                                                       fg="#78A817", )
        self.can_time_stamp_show_input.place(relx=0.89, rely=0.02, relwidth=0.1, relheight=0.05)
        # 天气
        self.weather_stamp_show1 = tkinter.Label(self.window, text=' ', font="等线 16 bold", background="#1E1F22",
                                                 fg="#58A2D5", highlightbackground="#a9b7c6")
        self.weather_stamp_show1.place(relx=0.75, rely=0.075, relwidth=0.03, relheight=0.025)
        self.weather_stamp_show2 = tkinter.Label(self.window, text=' ', font="等线 16 bold", background="#1E1F22",
                                                 fg="#58A2D5", highlightbackground="#a9b7c6")
        self.weather_stamp_show2.place(relx=0.78, rely=0.075, relwidth=0.03, relheight=0.025)
        self.weather_stamp_show3 = tkinter.Label(self.window, text='  度', font="等线 16 bold", background="#1E1F22",
                                                 fg="#58A2D5", highlightbackground="#a9b7c6")
        self.weather_stamp_show3.place(relx=0.81, rely=0.075, relwidth=0.03, relheight=0.025)

        self.weather_stamp_show4 = tkinter.Label(self.window, text='风向:xx', font="等线 16 bold",
                                                 background="#1E1F22",
                                                 fg="#58A2D5", highlightbackground="#a9b7c6")
        self.weather_stamp_show4.place(relx=0.84, rely=0.075, relwidth=0.05, relheight=0.025)
        self.weather_stamp_show5 = tkinter.Label(self.window, text='风力<=0级', font="等线 16 bold",
                                                 background="#1E1F22",
                                                 fg="#58A2D5", highlightbackground="#a9b7c6")
        self.weather_stamp_show5.place(relx=0.89, rely=0.075, relwidth=0.05, relheight=0.025)

        self.weather_stamp_show6 = tkinter.Label(self.window, text='湿度:00%', font="等线 16 bold",
                                                 background="#1E1F22",
                                                 fg="#58A2D5", highlightbackground="#a9b7c6")
        self.weather_stamp_show6.place(relx=0.94, rely=0.075, relwidth=0.05, relheight=0.025)

        # 时间相关
        self.time_stamp_show = tkinter.Label(self.window, text='时间戳', font="等线 16 bold", background="#1E1F22",
                                             foreground="#a9b7c6")
        self.time_stamp_show.place(relx=0.01, rely=0.1, relwidth=0.14, relheight=0.07, )
        self.time_stamp_input = tkinter.Entry(self.window, font="等线 16 bold", background="#1E1F22",
                                              foreground="#a9b7c6",
                                              borderwidth=1,
                                              highlightthickness=1, highlightbackground="#a9b7c6", relief=SOLID, )
        self.time_stamp_input.place(relx=0.01, rely=0.15, relwidth=0.14, relheight=0.05)

        self.time_formate_show = tkinter.Label(self.window, text='时间格式', font="等线 16 bold", background="#1E1F22",
                                               foreground="#a9b7c6")
        self.time_formate_show.place(relx=0.15, rely=0.1, relwidth=0.14, relheight=0.07, )
        self.time_formate_input = tkinter.Entry(self.window, font="等线 16 bold", justify="center",
                                                background="#1E1F22",
                                                foreground="#a9b7c6", borderwidth=1,
                                                highlightthickness=1, highlightbackground="#a9b7c6", relief=SOLID, )
        self.time_formate_input.place(relx=0.15, rely=0.15, relwidth=0.14, relheight=0.05)

        self.timestamp_to_formate = tkinter.Button(self.window, text="时间戳-->格式化",
                                                   command="handle_timestamp_formate",
                                                   activebackground="#0f73ef", borderwidth=1, highlightthickness=1,
                                                   relief=SOLID,
                                                   highlightbackground="#a9b7c6",
                                                   font="等线 16 bold", background="#1E1F22", foreground="#a9b7c6")
        self.timestamp_to_formate.bind("<Button-1>", self.handle_timestamp_formate)
        self.timestamp_to_formate.place(relx=0.01, rely=0.2, relwidth=0.14, relheight=0.05)

        self.formate_to_timestamp = tkinter.Button(self.window, text="时间格式-->时间戳",
                                                   command="handle_formate_timestamp",
                                                   activebackground="#0f73ef", borderwidth=1, highlightthickness=1,
                                                   relief=SOLID,
                                                   font="等线 16 bold", background="#1E1F22", foreground="#a9b7c6")
        self.formate_to_timestamp.bind("<Button-1>", self.handle_formate_timestamp)
        self.formate_to_timestamp.place(relx=0.15, rely=0.2, relwidth=0.14, relheight=0.05)

        self.last_print_text = tkinter.Text(self.window, width=40, height=10, border=4, relief=SOLID,
                                            font="等线 16 bold",
                                            bg="#1E1F22",
                                            fg="#99C794", borderwidth=1, highlightthickness=1,
                                            highlightbackground="#a9b7c6",
                                            highlightcolor="#a9b7c6")
        self.last_print_text.place(relx=0.01, rely=0.25, relwidth=0.28, relheight=0.1)

        self.clp_text = tkinter.Button(self.window, text="复制到粘贴板",
                                       command=self.copy_to_clipboard, activebackground="#0f73ef", font="等线 16 bold",
                                       background="#1E1F22", foreground="#a9b7c6")
        self.clp_text.place(relx=0.01, rely=0.35, relwidth=0.28, relheight=0.05)

        # 添加下拉框
        self.xiala_button = ttk.Combobox(self.window, font="等线 16 bold", background="#1E1F22", foreground="#a9b7c6",
                                         values=["节日倒数", "今日热榜", "历史今天"], )
        self.xiala_button.place(relx=0.01, rely=0.42, relwidth=0.06, relheight=0.05)
        self.xiala_button.current(0)
        self.xiala_button.bind('<<ComboboxSelected>>', self.on_combobox_selected)

        self.last_print_text_answer = tkinter.Text(self.window, width=40, height=10, border=4, relief=SOLID,
                                                   font="等线 13 bold",
                                                   bg="#1E1F22", fg="#99C794", borderwidth=1, highlightthickness=1,
                                                   highlightbackground="#a9b7c6",
                                                   highlightcolor="#a9b7c6")
        self.last_print_text_answer.place(relx=0.01, rely=0.50, relwidth=0.28, relheight=0.45)

        # 右边
        self.sting_input = tkinter.Entry(self.window, font="等线 16 bold", bg="#1E1F22",
                                         fg="#a9b7c6", borderwidth=1, highlightthickness=1,
                                         highlightbackground="#a9b7c6",
                                         highlightcolor="#a9b7c6", relief=SOLID, )
        self.sting_input.place(relx=0.3, rely=0.1, relwidth=0.24, relheight=0.05)

        self.sting_input_button = tkinter.Button(self.window, text="Json格式化", activebackground="#0f73ef",
                                                 font="等线 16 bold",
                                                 bg="#1E1F22", fg="#a9b7c6")
        self.sting_input_button.bind("<Button-1>", self.handle_to_json)
        self.sting_input_button.place(relx=0.54, rely=0.1, relwidth=0.055, relheight=0.05)

        self.sting_auto_trans_en_button = tkinter.Button(self.window, text="中-->英", activebackground="#0f73ef",
                                                         font="等线 16 bold",
                                                         bg="#1E1F22", fg="#a9b7c6")
        self.sting_auto_trans_en_button.bind("<Button-1>", lambda event, text=True: self.handle_auto_translate(text))
        self.sting_auto_trans_en_button.place(relx=0.595, rely=0.1, relwidth=0.05, relheight=0.05)
        self.sting_auto_trans_cn_button = tkinter.Button(self.window, text="英-->中", activebackground="#0f73ef",
                                                         font="等线 16 bold",
                                                         bg="#1E1F22", fg="#a9b7c6")
        self.sting_auto_trans_cn_button.bind("<Button-1>", lambda event, text=False: self.handle_auto_translate(text))
        self.sting_auto_trans_cn_button.place(relx=0.645, rely=0.1, relwidth=0.05, relheight=0.05)
        self.sting_clean_button = tkinter.Button(self.window, text="清空", command="handle_formate_timestamp",
                                                 activebackground="#0f73ef",
                                                 font="等线 16 bold", bg="#1E1F22", fg="#a9b7c6")
        self.sting_clean_button.bind("<Button-1>", self.clean_input)
        self.sting_clean_button.place(relx=0.695, rely=0.1, relwidth=0.0375, relheight=0.05)

        self.clp_json = tkinter.Button(self.window, text="复制",
                                       command=self.copy_to_json_clipboard, activebackground="#0f73ef",
                                       font="等线 16 bold",
                                       bg="#1E1F22",
                                       fg="#a9b7c6")
        self.clp_json.place(relx=0.7325, rely=0.1, relwidth=0.0375, relheight=0.05)

        self.show_upload_speed = tkinter.Label(self.window, text='', font="等线 14 bold", bg="#1E1F22", fg="#a9b7c6",
                                               borderwidth=1,
                                               highlightthickness=1, relief=SOLID, highlightbackground="#a9b7c6")
        self.show_upload_speed.place(relx=0.77, rely=0.1, relwidth=0.06, relheight=0.05)

        self.show_download_speed = tkinter.Label(self.window, text='', font="等线 14 bold", bg="#1E1F22", fg="#a9b7c6",
                                                 borderwidth=1,
                                                 highlightthickness=1, relief=SOLID, highlightbackground="#a9b7c6")
        self.show_download_speed.place(relx=0.83, rely=0.1, relwidth=0.06, relheight=0.05)

        self.show_cpu_ = tkinter.Label(self.window, text='', font="等线 14 bold", bg="#1E1F22", fg="#a9b7c6",
                                       borderwidth=1,
                                       highlightthickness=1, relief=SOLID, highlightbackground="#a9b7c6")
        self.show_cpu_.place(relx=0.89, rely=0.1, relwidth=0.05, relheight=0.05)

        self.show_memory_label = tkinter.Label(self.window, text='', font="等线 14 bold", bg="#1E1F22", fg="#a9b7c6",
                                               borderwidth=1,
                                               highlightthickness=1, relief=SOLID, highlightbackground="#a9b7c6")
        self.show_memory_label.place(relx=0.94, rely=0.1, relwidth=0.05, relheight=0.05)

        self.sting_output_button = tkinter.Text(self.window, width=40, height=10, border=4, relief=SOLID,
                                                font="等线 16 bold",
                                                bg="#1E1F22", fg="#99C794", borderwidth=1, highlightthickness=1,
                                                highlightbackground="#a9b7c6")
        self.sting_output_button.place(relx=0.3, rely=0.15, relwidth=0.69, relheight=0.8)

        # 壁纸设置
        self.desktop_picture_button = tkinter.Button(self.window, padx=5, activebackground="#0f73ef", text="Bing壁纸",
                                                     command=self.set_desktop_picture,
                                                     font="等线 16 bold", bg="#1E1F22", fg="#78A817", borderwidth=1,
                                                     highlightthickness=1,
                                                     relief=SOLID, )
        self.desktop_picture_button.pack()
        self.desktop_picture_button.place(relx=0.9, rely=0.95, relwidth=0.05, relheight=0.03)
        switch_obj = db_session.query(System_info).filter_by(name="switch").first()
        self.switch_var = tkinter.BooleanVar(value=True if switch_obj.value == 1 else False)
        self.switch = Checkbutton(self.window, text="On/Off", command=self.on_switch_change, variable=self.switch_var)
        self.switch.place(relx=0.95, rely=0.95, relwidth=0.05, relheight=0.03)
        # 我想要创建一个sqlite数据库，用来记录json格式化后的内容

        # 添加成长切换
        self.growth_input = DateEntry(self.window, bootstyle="success", dateformat='%Y-%m-%d %H:%M:%S',
                                      startdate=datetime.datetime.strptime(growth_date, '%Y-%m-%d %H:%M:%S'))
        self.growth_input.place(relx=0.65, rely=0.95, relwidth=0.1, relheight=0.03)
        self.growth_submit = tkinter.Button(self.window, text="提交", command="get_time_submit_method",
                                            activebackground="#0f73ef", borderwidth=1, highlightthickness=1,
                                            relief=SOLID,
                                            highlightbackground="#a9b7c6",
                                            font="等线 12 bold", background="#1E1F22", foreground="#a9b7c6")
        self.growth_submit.bind("<Button-1>", self.get_time_submit_method)
        self.growth_submit.place(relx=0.75, rely=0.95, relwidth=0.05, relheight=0.03)
        self.growth_show = tkinter.Label(self.window, text='', font="等线 19 bold", background="#1E1F22",
                                         fg="#78A817", )
        self.growth_show.place(relx=0.8, rely=0.95, relwidth=0.1, relheight=0.03)

    def start(self):
        self.get_current_weather()
        # 创建一个线程池执行器
        # executor = ThreadPoolExecutor(max_workers=1)
        resource_thread = threading.Thread(target=self.get_resource_usage, args=(result_queue,))
        resource_thread.daemon = True  # Daemonize thread so it will be automatically killed when main program exits
        resource_thread.start()
        self.get_now_time()
        # 在主循环中开始更新过程
        self.handle_memory_cpu()
        self.can_time_stamp_show()
        self.set_ad_code()

    def get_time_submit_method(self, event):
        """
        :return:
        """
        if self.can_time_stamp_input.entry.get():
            pick_time = self.can_time_stamp_input.entry.get()
            if pick_date != pick_time:
                pick = db_session.query(System_info).filter_by(name="pick_date").first()
                pick.text = pick_time
                db_session.commit()
        if self.growth_input.entry.get():
            growth_time = self.growth_input.entry.get()
            if growth_date != growth_time:
                growth = db_session.query(System_info).filter_by(name="growth_date").first()
                growth.text = growth_time
                db_session.commit()
        self.handle_calculator_time()

    def handle_timestamp_formate(self, event):
        if self.time_stamp_input.get():
            need_time = self.time_stamp_input.get().strip()
            time_local = time.localtime(int(need_time))  # 转化成localtime
            time_format = time.strftime("%Y-%m-%d %H:%M:%S", time_local)
            self.last_print_text.delete('1.0', END)
            self.last_print_text.insert(END, "\n", "center")  # ADDED
            self.last_print_text.insert(END, "\n", "center")  # ADDED
            self.last_print_text.insert(END, "                   " + str(time_format), "center")
        else:
            now_time = int(time.time())
            time_local = time.localtime(now_time)  # 转化成localtime
            time_format = time.strftime("%Y-%m-%d %H:%M:%S", time_local)
            self.last_print_text.delete('1.0', END)
            self.last_print_text.insert(END, "\n", "center")  # ADDED
            self.last_print_text.insert(END, "\n", "center")  # ADDED
            self.last_print_text.insert(END, "                   " + str(time_format), "center")

    def handle_formate_timestamp(self, event):
        if self.time_formate_input.get():
            formate_data = self.time_formate_input.get().strip()
            if len(formate_data) == 10:
                # 转换成时间数组
                time_array = time.strptime(formate_data, "%Y-%m-%d")
                # 转换成时间戳
                time_format = int(time.mktime(time_array))
                self.last_print_text.delete('1.0', END)
                self.last_print_text.insert(END, "\n", "center")  # ADDED
                self.last_print_text.insert(END, "\n", "center")  # ADDED
                self.last_print_text.insert(END, "                           " + str(time_format), "center")
            elif len(formate_data) == 19:  # "2023-03-21 15:11:25"
                time_array = time.strptime(formate_data, "%Y-%m-%d %H:%M:%S")
                # 转换成时间戳
                time_format = int(time.mktime(time_array))
                self.last_print_text.delete('1.0', END)
                self.last_print_text.insert(END, "\n", "center")  # ADDED
                self.last_print_text.insert(END, "\n", "center")  # ADDED
                self.last_print_text.insert(END, "                           " + str(time_format), "center")
            elif len(formate_data) == 16:  # "2023-04-01 14:00"
                time_array = time.strptime(formate_data, "%Y-%m-%d %H:%M")
                # 转换成时间戳
                time_format = int(time.mktime(time_array))
                self.last_print_text.delete('1.0', END)
                self.last_print_text.insert(END, "\n", "center")  # ADDED
                self.last_print_text.insert(END, "\n", "center")  # ADDED
                self.last_print_text.insert(END, "                           " + str(time_format), "center")
        else:
            now_time = int(time.time())
            self.last_print_text.delete('1.0', END)
            self.last_print_text.insert(END, "\n", "center")  # ADDED
            self.last_print_text.insert(END, "\n", "center")  # ADDED
            self.last_print_text.insert(END, "                           " + str(now_time), "center")  # ADDED

    def handle_to_json(self, event):
        if self.sting_input.get():
            need_time = self.sting_input.get().strip()
            self.sting_output_button.delete('1.0', END)
            try:
                need_time = need_time.replace("'", '"')
                need_time = json.loads(need_time)
                last_send = json.dumps(need_time, ensure_ascii=False, indent=4, separators=(',', ':'))
                self.sting_output_button.insert(END, last_send, "center")  # ADDED
            except Exception as e:
                self.sting_output_button.delete('1.0', END)
                self.sting_output_button.insert(END, "字符串格式有误，请确认字符串使用的是为双引号\n", "center")  # ADDED
        else:
            self.sting_output_button.delete('1.0', END)
            self.sting_output_button.insert(END, "请在左边输入需要转化的字符串\n", "center")  # ADDED

    def handle_auto_translate(self, is_en_to_zh=False):
        if self.sting_input.get():
            user_input = self.sting_input.get().strip()
            if user_input == "":
                self.sting_output_button.delete('1.0', END)
                self.sting_output_button.insert(END, "请在左边输入需要转化的字符串\n", "center")  # ADDED
            self.sting_output_button.delete('1.0', END)
            try:
                if not is_en_to_zh:
                    from_lang = 'en'
                    to_lang = 'zh'
                else:
                    from_lang = 'zh'
                    to_lang = 'en'
                # 生成随机数salt
                salt = str(random.randint(32768, 65536))
                # 拼接字符串1
                sign_string = app_id + user_input + salt + secret_key_fy

                # 对字符串1做MD5加密
                sign = hashlib.md5(sign_string.encode()).hexdigest()

                # 拼接完整的请求URL
                url = f'http://api.fanyi.baidu.com/api/trans/vip/translate?q={user_input}&from={from_lang}&to={to_lang}&appid={app_id}&salt={salt}&sign={sign}'

                # 发送GET请求
                response = requests.get(url)

                translated_text = "请稍后重试"
                # 解析响应数据
                if response.status_code == 200:
                    result = response.json()
                    translated_text = result['trans_result'][0]['dst']
                    translated_text = translated_text.replace(" ", "_")
                self.sting_output_button.insert(END, translated_text, "center")  # ADDED
            except Exception as e:
                self.sting_output_button.delete('1.0', END)
                self.sting_output_button.insert(END, "API异常\n", "center")  # ADDED
        else:
            self.sting_output_button.delete('1.0', END)
            self.sting_output_button.insert(END, "请在左边输入需要转化的字符串\n", "center")  # ADDED

    def handle_chat_message(self, ):
        chat_message = self.sting_input.get().strip()
        key = api_key.strip()
        sec_key = secret_key_wx.strip()
        if key and sec_key:
            if chat_message:
                if key and sec_key:
                    url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token=" + get_access_token(
                        api_key, secret_key_wx)
                    payload = json.dumps({
                        "messages": [
                            {"role": "user", "content": f"{chat_message}"}]})
                    headers = {'Content-Type': 'application/json'}
                    response = requests.request("POST", url, headers=headers, data=payload)
                    response_message = response.json().get("result")
                    self.sting_output_button.delete('1.0', END)
                    self.sting_output_button.insert(END, response_message, "center")  # ADDED
            else:
                self.sting_output_button.delete('1.0', END)
                self.sting_output_button.insert(END, "请在左边输入想要查询的问题\n", "center")  # ADDED
        else:
            self.sting_output_button.delete('1.0', END)
            self.sting_output_button.insert(END, "请先配置api_key,secret_key\n", "center")  # ADDED

    def start_request_baidu(self, ):
        global request_thread
        if request_thread is None:
            download_thread = threading.Thread(target=self.handle_chat_message)
            download_thread.start()

    def clean_input(self, event):
        self.sting_input.delete(0, END)

    def listbox_copy(self, event):
        self.window.clipboard_clear()
        selected = self.last_print_text.get(ANCHOR)
        selected = selected.strip()
        self.window.clipboard_append(selected)

    def copy_to_clipboard(self, ):
        """Copy current contents of text_entry to clipboard."""
        self.window.clipboard_clear()  # Optional.
        self.window.clipboard_append(self.last_print_text.get('1.0', END).rstrip().strip())

    def copy_to_json_clipboard(self, ):
        """Copy current contents of text_entry to clipboard."""
        self.window.clipboard_clear()  # Optional.
        self.window.clipboard_append(self.sting_output_button.get('1.0', END).rstrip().strip())

    def get_now_time(self, ):
        time_str = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')  # 获取当前的时间并转化为字符串
        # 切换冒号的显示状态
        global global_time_status
        if not global_time_status:
            time_str = time_str.replace(':', ' ')
            global_time_status = True
        else:
            global_time_status = False
        week_int = datetime.datetime.now().weekday()  # 获取当前的时间并转化为字符串
        date_dict = {0: "星期一", 1: "星期二", 2: "星期三", 3: "星期四", 4: "星期五", 5: "星期六", 6: "星期日", }
        week_str = date_dict.get(week_int)
        self.now_time_label.configure(text=time_str)  # 重新设置标签文本
        self.dat_num_label.configure(text=week_str)  # 重新设置标签文本
        self.window.after(1000, self.get_now_time)  # 每隔1s调用函数 get_now_time 自身获取时间

    def get_current_weather(self, ):
        code = ad_code
        key = gaode_key
        # 1.获取API
        url = f"https://restapi.amap.com/v3/weather/weatherInfo?city={code}&key={key}&output=JSON&extensions=base"
        res = urlopen(url)
        data = json.loads(res.read())
        # province = data['lives'][0]['province']  # 省份
        city = data['lives'][0]['city']  # 城市
        weather = data['lives'][0]['weather']  # 天气情况
        temperature = data['lives'][0]['temperature']  # 温度
        winddirection = data['lives'][0]['winddirection']  # 风向
        windpower = data['lives'][0]['windpower']  # 风力 级
        humidity = data['lives'][0]['humidity']  # 空气湿度
        self.weather_stamp_show1.configure(text=city)  # 重新设置标签文本
        self.weather_stamp_show2.configure(text=weather)  # 重新设置标签文本
        self.weather_stamp_show3.configure(text=str(temperature) + '°C')  # 重新设置标签文本
        self.weather_stamp_show4.configure(text=f"风向:{winddirection}")  # 重新设置标签文本
        self.weather_stamp_show5.configure(text=f"风力:{windpower}级")  # 重新设置标签文本
        self.weather_stamp_show6.configure(text=f"湿度:{humidity}%")  # 重新设置标签文本
        switch_obj = db_session.query(System_info).filter_by(name="switch").first()
        if switch_obj.value == 1:
            thread = BingUHD(self.set_desktop_picture)
            thread.start()
        self.window.after(1000 * 60 * 60 * 6, self.get_current_weather)  # 6小时更新一次天气信息

    def set_ad_code(self):
        # 获取定位和adcode
        try:
            url = f"https://restapi.amap.com/v3/ip?key={gaode_key}"
            response = requests.get(url)
            response.raise_for_status()  # 检查HTTP错误
            data = response.json()

            if data["status"] != "1":
                pass
            else:
                ad_code = data["adcode"]
                now_ad_code = self.session.query(System_info).filter_by(name="ad_code").first().value
                if ad_code != now_ad_code:
                    self.session.query(System_info).filter_by(name="ad_code").update({"value": ad_code})
                    self.session.commit()
                    # self.get_current_weather()
                # raise ValueError(f"API错误: {data['info']}")
            # return {
            #     "province": data["province"],
            #     "city": data["city"],
            #     "adcode": data["adcode"],
            #     "location": data["rectangle"].split(";")[0]  # 取第一个坐标点
            # }
        except requests.exceptions.RequestException as e:
            print(f"网络请求失败: {e}")
            return None
        except ValueError as e:
            print(e)
            return None

    # 定义一个函数，用于在后台线程中获取CPU和内存使用率
    def get_resource_usage(self, queue):
        """
        Retrieves CPU and memory usage metrics and stores them in a queue.
        """
        while True:
            interval = 0.5
            cpu_percent = psutil.cpu_percent(interval=1)
            memory_percent = psutil.virtual_memory().percent
            # 获取网络IO统计信息
            net_io = psutil.net_io_counters(pernic=True)

            # 初始化上传和下载的字节数
            total_upload_before = 0
            total_download_before = 0

            # 遍历所有网络接口并累加上传和下载的字节数
            for interface in net_io:
                if "以太网" in interface or "Ethernet" in interface:
                    total_upload_before += net_io[interface].bytes_sent
                    total_download_before += net_io[interface].bytes_recv

            # 暂停一段时间
            time.sleep(interval)

            # 再次获取网络IO统计信息
            net_io = psutil.net_io_counters(pernic=True)

            # 初始化上传和下载的增量
            total_upload_after = 0
            total_download_after = 0

            # 遍历所有网络接口并累加上传和下载的增量
            for interface in net_io:
                if "以太网" in interface or "Ethernet" in interface:
                    total_upload_after += net_io[interface].bytes_sent
                    total_download_after += net_io[interface].bytes_recv

            # 计算总的上传和下载速度（单位：KB/s）
            total_upload_speed = (total_upload_after - total_upload_before) / 1024 / interval
            total_download_speed = (total_download_after - total_download_before) / 1024 / interval

            queue.put((cpu_percent, memory_percent, total_upload_speed, total_download_speed))
            time.sleep(1)

    def handle_memory_cpu(self, ):
        """
        处理内存和CPU显示
        :return:
        """
        try:
            cpu_nums, memory_nums, total_upload_speed, total_download_speed = result_queue.get_nowait()
            cpu_color = "#58A2D5"
            memory_color = "#9AC733"
            up_color = "#FA9014"
            down_color = "#FA9014"
            if int(cpu_nums) > 80:
                cpu_color = "#CB1B04"
            if int(memory_nums) > 80:
                memory_color = "#CB1B04"
            if total_upload_speed >= 1024:
                total_upload_speed /= 1024
                upload_unit = "MB/s"
                up_color = "#CB1B04"
            else:
                upload_unit = "KB/s"

            if total_download_speed >= 1024:
                total_download_speed /= 1024
                download_unit = "MB/s"
                down_color = "#CB1B04"
            else:
                download_unit = "KB/s"

            self.show_upload_speed.configure(text=f"↑:{total_upload_speed:.2f}{upload_unit}", fg=up_color)
            self.show_download_speed.configure(text=f"↓:{total_download_speed:.2f}{download_unit}", fg=down_color)
            self.show_cpu_.configure(text=f"CPU:{cpu_nums}%", fg=cpu_color)  # 重新设置标签文本
            self.show_memory_label.configure(text=f"内存:{memory_nums}%", fg=memory_color)  # 重新设置标签文本

        except queue.Empty:
            pass
        self.window.after(1000, self.handle_memory_cpu)

    def local_day_laster(self, ):
        send = day_laster()
        self.last_print_text_answer.delete('1.0', END)
        self.last_print_text_answer.insert(END, send, "center")  # ADDED

    def set_desktop_picture(self, ):
        """
        设置桌面壁纸
        :return:
        """
        path = './BingUHD/'
        today = datetime.datetime.now()
        yesterday = today - datetime.timedelta(days=1)
        file_name = path + str(yesterday.strftime("%Y%m%d")) + "3840x2160.jpg"
        current_dir = os.getcwd()
        relative_path = os.path.join(current_dir, file_name)
        if not os.path.exists(file_name):
            thread = BingUHD(self.set_desktop_picture)
            thread.start()
        if os.path.exists(file_name):
            k = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, "Control Panel\\Desktop", 0, win32con.KEY_SET_VALUE)
            win32api.RegSetValueEx(k, "WallpaperStyle", 0, win32con.REG_SZ, "2")  # 2拉伸适应桌面，0桌面居中
            win32api.RegSetValueEx(k, "TileWallpaper", 0, win32con.REG_SZ, "0")
            win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, relative_path, 1 + 2)

    def on_switch_change(self, ):
        """
        壁纸切换
        :return:
        """
        switch_obj = db_session.query(System_info).filter_by(name="switch").first()
        if self.switch_var.get():
            switch_obj.value = 1
            db_session.commit()
            self.set_desktop_picture()
        else:
            switch_obj.value = 0
            db_session.commit()

    # 示例的界面更新函数
    def update_gui(self, news):
        # 实现更新界面的逻辑，例如更新文本框或标签
        self.last_print_text_answer.delete('1.0', END)
        self.last_print_text_answer.insert(END, news + "\n")

    def local_get_today(self, ):
        urls = [['https://tophub.today/c/news', "today"]]
        thread = NewsUpdaterThread(urls, self.update_gui)
        thread.start()

    def local_get_hot_news(self, ):
        urls = [['https://tophub.today/c/news', "hot"]]
        thread = NewsUpdaterThread(urls, self.update_gui)
        thread.start()

    def get_system_info(self, names):
        """批量查询System_info表中的记录"""
        result = self.session.query(System_info).filter(System_info.name.in_(names)).all()
        return {item.name: item.text for item in result}

    def format_time_difference(self, td):
        """格式化时间差为天、小时、分钟"""
        days = td.days
        hours, remainder = divmod(td.seconds, 3600)
        minutes, _ = divmod(remainder, 60)
        return f"差:{days}天{hours}时{minutes}分"

    def calculate_growth_days(self, td):
        """计算成长天数"""
        return f"成长了{td.days}天"

    def handle_calculator_time(self):
        try:
            # 批量查询所需数据
            info_dict = self.get_system_info(["pick_date", "growth_date"])
            # 获取并解析时间字符串
            need_time = info_dict.get("pick_date")
            growth_date = info_dict.get("growth_date")
            if not need_time or not growth_date:
                raise ValueError("缺少必要的日期信息")
            need_time_obj = datetime.datetime.strptime(need_time, '%Y-%m-%d %H:%M:%S')
            growth_time_obj = datetime.datetime.strptime(growth_date, '%Y-%m-%d %H:%M:%S')
            now = datetime.datetime.now()
            # 计算时间差
            time_diff = need_time_obj - now
            growth_diff = now - growth_time_obj
            # 格式化输出
            show_string = self.format_time_difference(time_diff)
            growth_show_string = self.calculate_growth_days(growth_diff)
            self.can_time_stamp_show_input.configure(text=show_string)  # 重新设置标签文本
            self.growth_show.configure(text=growth_show_string)  # 重新设置标签文本

        except (AttributeError, ValueError) as e:
            print(f"处理时间时发生错误: {e}")
            self.can_time_stamp_show_input.configure(text="错误：无法计算时间差")
            self.growth_show.configure(text="错误：无法计算成长天数")

    def can_time_stamp_show(self):
        try:
            self.handle_calculator_time()
        except Exception as e:
            show_string = "输入有误"
            self.can_time_stamp_show_input.configure(text=show_string)  # 重新设置标签文本
        self.window.after(60 * 1000, self.can_time_stamp_show)  # 每隔1s调用函数 get_now_time 自身获取时间

    def on_combobox_selected(self, event):
        # 获取选中的值
        selected_value = self.xiala_button.get()
        print(f"Selected value: {selected_value}")
        if selected_value == "今日热榜":
            self.local_get_hot_news()
        elif selected_value == "节日倒数":
            self.local_day_laster()
        elif selected_value == "历史今天":
            self.local_get_today()
        # 在这里执行你需要的操作


class NewsUpdaterThread(threading.Thread):
    def __init__(self, urls, callback):
        threading.Thread.__init__(self)
        self.urls = urls
        self.callback = callback
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36"}

    def run(self):
        now = datetime.datetime.now()
        formatted_date = now.strftime('%Y%m%d')
        for url in self.urls:
            try:
                existing_record = db_session.query(Day_info).filter_by(this_date=formatted_date, key=url[1]).first()
                if not existing_record:
                    last_send = []
                    response = requests.get(url[0], headers=self.headers)
                    html = response.text
                    return_list = get_content(html, "news", url[1])
                    last_send = last_send + return_list
                    last_send.append("---------------------------")
                    last_content = "认认真真上班，这根本就不叫赚钱，那是用劳动换取报酬。"
                    _last_content = "人活半辈子才明白，真正高级的养生，是回家好好吃饭"
                    _last_content0 = "别沮丧，生活就像心电图，一帆风顺就证明你挂了！"
                    _last_content1 = "最后，祝愿天下所有摸鱼人，都能愉快的渡过每一天!"
                    _last_content2 = "关注我，这样每天我都能见到你了"
                    _last_content3 = "我是 【捣蛋小能手】 捣蛋的捣 & 捣蛋的蛋 ! "
                    _last_content4 = "email:henry_oulen@163.com"

                    last_send.append(last_content)
                    last_send.append(_last_content)
                    last_send.append(_last_content0)
                    last_send.append(_last_content1)
                    last_send.append(_last_content2)
                    last_send.append(_last_content3)
                    last_send.append(_last_content4)
                    new_record = Day_info(this_date=formatted_date, key=url[1],
                                          content=json.dumps(last_send, ensure_ascii=False))
                    db_session.add(new_record)
                    db_session.commit()
                else:
                    last_send = db_session.query(Day_info).filter_by(this_date=formatted_date,
                                                                     key=url[1]).first().content
                    last_send = json.loads(last_send)
                    if not last_send:
                        response = requests.get(url[0], headers=self.headers)
                        html = response.text
                        return_list = get_content(html, "news", url[1])
                        last_send = last_send + return_list
                        last_send.append("---------------------------")
                        last_content = "认认真真上班，这根本就不叫赚钱，那是用劳动换取报酬。"
                        _last_content = "人活半辈子才明白，真正高级的养生，是回家好好吃饭"
                        _last_content0 = "别沮丧，生活就像心电图，一帆风顺就证明你挂了！"
                        _last_content1 = "最后，祝愿天下所有摸鱼人，都能愉快的渡过每一天!"
                        _last_content2 = "关注我，这样每天我都能见到你了"
                        _last_content3 = "我是 【捣蛋小能手】 捣蛋的捣 & 捣蛋的蛋 ! "
                        _last_content4 = "email:henry_oulen@163.com"
                        last_send.append(last_content)
                        last_send.append(_last_content)
                        last_send.append(_last_content0)
                        last_send.append(_last_content1)
                        last_send.append(_last_content2)
                        last_send.append(_last_content3)
                        last_send.append(_last_content4)
                send = ""
                for i in last_send:
                    send += i + "\r\n"
                self.callback(send)
            except requests.RequestException as e:
                print(f"Error fetching {url}: {e}")


class BingUHD(threading.Thread):

    def __init__(self, callback):
        threading.Thread.__init__(self)
        # 默认bing图片查询地址
        self.url = 'https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=ZH-CN'
        self.path = './BingUHD/'
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                          'Chrome/80.0.3987.132 Safari/537.36'}
        self.resolution = 'UHD'
        self.callback = callback

    # 取得图片相关信息
    def get_img_info(self):
        try:
            # 获取图片信息
            result = requests.get(self.url, headers=self.headers).json()
            # 提取图片地址
            raw_img_url = 'https://cn.bing.com' + result['images'][0]['url']
            normal_img_url = raw_img_url[0:raw_img_url.find(".jpg") + 4]
            uhd_img_url = normal_img_url.replace("1920x1080", self.resolution)
            # 提取中文标题和版权信息
            date = result["images"][0]["startdate"]
            title = result["images"][0]["title"]
            copy_right = result["images"][0]["copyright"]
            return normal_img_url, uhd_img_url, date, title, copy_right

        except Exception as e:
            print('错误: 无法获取到图片地址，请检查网络连接' + '\n')

    def img_download(self, url, file_name):
        try:
            response = requests.get(url, stream=True)
            if response.status_code == 200:
                with open(file_name, 'wb') as file_stream:
                    response.raw.decode_content = True
                    shutil.copyfileobj(response.raw, file_stream)
                print(file_name + "图片下载成功")
            else:
                print(file_name + "无法下载图片")
        except Exception:
            print('错误: 无法下载图片，请检查网络连接' + '\n')

    # 得到今日图片信息并清洗
    def get_today_img_download(self, file_name):
        try:
            info = self.get_img_info()
            uhd_url = info[1]
            uhd = self.get_pic_size()[1]
            self.img_download(uhd_url, file_name + uhd + '.jpg')
        except Exception:
            print('错误: 无法获取到图片信息，请检查网络连接' + '\n')

    # 取得文件名称
    def get_file_name(self):
        try:
            info = self.get_img_info()
            # 定义文件夹
            file_path = self.path + '/'
            # 判断文件夹是否存在
            if not os.path.exists(file_path):
                os.makedirs(file_path)
            # 定义文件名
            name = info[2]
            full_name = file_path + name
            return full_name
        except Exception:
            print('错误: 无法获取到图片信息，请检查网络连接' + '\n')

    # 取得图片的尺寸
    def get_pic_size(self):
        """
        获取远程图片的尺寸
        :return:
        """
        size_list = []
        url = [self.get_img_info()[0], self.get_img_info()[1]]
        for u in url:
            r = requests.get(u)
            img = Image.open(BytesIO(r.content))
            pic_size = str(img.width) + 'x' + str(img.height)
            size_list.append(pic_size)
        return size_list

    # 取得今日美图文字
    def get_description(self):
        url = 'https://www.bing.com/?mkt=zh-CN'
        rsp = requests.get(url)
        result = re.search(r'({"Description":")(.*?)(","Image")', rsp.text).group(2)
        return result

    def run(self):
        today = datetime.datetime.now()
        yesterday = today - datetime.timedelta(days=1)
        file_name = self.path + str(yesterday.strftime("%Y%m%d")) + "3840x2160.jpg"
        if not os.path.exists(file_name):
            down_file_name = self.get_file_name()
            self.get_today_img_download(down_file_name)
        switch_obj = db_session.query(System_info).filter_by(name="switch").first()
        if switch_obj.value == 1:
            time.sleep(10)
            self.callback()


if __name__ == '__main__':
    my_window = tkinter.Tk()
    Json_tools = JsonTools(my_window)
    Json_tools.start()
    # 启动主循环
    my_window.mainloop()
